/**
 * Project Name:cnsy-url-short-service
 * File Name:FreemarkerExceptionHandler.java
 * Package Name:cn.cnsy123.shorturls.business.exception 
 * Date: 2020年4月9日-下午6:43:06
 * Copyright (c) 2020, yangpengfei@360@126.com All Rights Reserved. 
 *
 */

package cn.cnsy123.shorturls.business.exception;

import java.io.PrintWriter;
import java.io.Writer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import freemarker.core.Environment;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

/**
 * ClassName: FreemarkerExceptionHandler
 * 
 * @author yangpengfei
 * @date 2020年4月9日-下午6:43:06
 * @version 1.0
 * @since JDK 1.7
 */
public class FreemarkerExceptionHandler implements TemplateExceptionHandler {

    @Override
    public void handleTemplateException(TemplateException te, Environment env, Writer out) throws TemplateException {
        if(!env.isInAttemptBlock()) {
            boolean externalPw = out instanceof PrintWriter;
            PrintWriter pw = externalPw ? (PrintWriter) out : new PrintWriter(out);
            try {
                StringBuilder errorPage = new StringBuilder();
                errorPage.append("解析失败,返回500");
                pw.println(errorPage.toString());
                pw.flush();
            }finally {
                if(null != pw) {
                    pw.close();
                }
            }
        }
        
    }

}
